package com.guigutool.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigutool.reggie.common.BaseContext;
import com.guigutool.reggie.common.CustomException;
import com.guigutool.reggie.entity.*;
import com.guigutool.reggie.mapper.OrderMapper;
import com.guigutool.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: KingWang
 * @Date: 2023/3/16
 * @Desc:
 **/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;


    @Transactional
    @Override
    public void submit(Order order) {

        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        if(Objects.isNull(shoppingCartList)||shoppingCartList.size() <= 0){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户信息
        User user = userService.getById(userId);
        //查询地址数据
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());
        if(Objects.isNull(addressBook)){
            throw new CustomException("用户地址为空，不能下单");
        }

        Long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(item->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId) ;
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item. getImage());
            orderDetail.setAmount(item.getAmount()) ;
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //订单号
        order.setId(orderId);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setStatus(2);
        order.setAmount(new BigDecimal(amount.get()));
        order.setUserId(userId);
        order.setNumber(String.valueOf(orderId));
        order.setUserName(user.getName());
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());

        String provinceName = addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName();
        String cityName = addressBook.getCityName() == null ? "" : addressBook.getCityName();
        String districtName = addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName();
        String detail = addressBook.getDetail() == null ? "" : addressBook.getDetail();
        order.setAddress(provinceName + cityName + districtName + detail);

        //保存订单
        this.save(order);
        //保存订单明细
        orderDetailService.saveBatch(orderDetailList);

        //删除购物车
        shoppingCartService.remove(wrapper);
    }
}
